<template>
  <ion-page>
    <ion-header>
      <ion-toolbar>
        <ion-buttons slot="start">
          <ion-button @click="toggleMode" class="mode-toggle">
            <div class="button-content">
              <span>{{ mode === 'day' ? 'WEEK' : 'DAY' }}</span>
              <ion-icon :icon="swapHorizontal" class="toggle-icon" />
            </div>
          </ion-button>
        </ion-buttons>
        <ion-buttons slot="end">  
          <ion-button @click="changeDate(-1)">
            <ion-icon :icon="chevronBack" />
          </ion-button>        
          <ion-button @click="isDatePickerOpen = true">
            {{ format(currentDate, 'yyyy MMM') }}
          </ion-button>
          <ion-button @click="changeDate(1)">
            <ion-icon :icon="chevronForward" />
          </ion-button>
          <ion-button @click="gotoLogs">Logs</ion-button>
        </ion-buttons>
      </ion-toolbar>
    </ion-header>
    <!-- 日期选择器弹窗 -->
    <ion-modal 
  :is-open="isDatePickerOpen" 
  @didDismiss="isDatePickerOpen = false"
  :css-class="'compact-date-picker'"
>
  <ion-content class="ion-padding">
    <ion-datetime
      presentation="date"
      :value="currentDate.toISOString()"
      @ionChange="handleDateChange"
      :show-default-title="false"
      :show-default-buttons="false"
      locale="en-US"
      class="compact-datetime"
    ></ion-datetime>
    <!-- <ion-buttons class="modal-buttons">
      <ion-button @click="isDatePickerOpen = false">Cancel</ion-button>
      <ion-button @click="isDatePickerOpen = false">OK</ion-button>
    </ion-buttons> -->
  </ion-content>
</ion-modal>
    <ion-content class="ion-padding">
      <!-- 周视图 -->
      <div v-if="mode === 'week'" class="calendar-week">
        <div class="week-scroll-container">
        <div class="week-header">
          <div v-for="day in weekDays" 
               :key="day.date.toString()"
               class="week-day"
               :class="{ 'today': day.isToday }">
            <div class="weekday-name">{{ day.weekday }}</div>
            <div class="date">{{ day.date.getDate() }}</div>
          </div>
        </div>
        <!-- 周视图 -->
        <div class="week-body">
          <div v-for="day in weekDays" 
               :key="day.date.toString()"
               class="day-column">
            <div v-for="schedules in getSchedules(day.date)"
                 :key="schedules.usId"
                 class="schedule-item"
                 :class="getScheduleStatus(schedules)"
                 @click="handleScheduleClick(schedules)">
              <div class="time">{{ schedules.startTime }}</div>
              <div class="details">
                <div class="name">{{ schedules.name }}</div>
                <div class="position">{{ schedules.position }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      </div>

      <!-- 日视图 -->
      <div v-else class="calendar-day">
        <div class="day-header">
          <div class="current-date">
            {{ format(currentDate, 'MMMM dd,yyyy') }}
          </div>
          <br>
          <div class="daytitle">
            {{ format(currentDate, 'EEEE') }}
          </div>
        </div>
        <!-- 时间轴 -->
        <div class="time-axis-container">
      <div 
        v-for="(slot, index) in timeSlots"
        :key="index"
        class="time-marker"
        :style="{ top: getMarkerPosition(slot) }"
      >
        <div class="time-label">
          {{ format(slot.start, 'ha') }}
        </div>
        <div class="time-line"></div>
      </div>
      
      <div 
        v-for="schedules in dailySchedules"
        :key="schedules.usId"
        class="schedule-block"
        :style="getScheduleBlockStyle(schedules)"
        :class="getScheduleStatus(schedules)"
      >
        <div class="schedule-content">
          <!-- <div class="time">
            {{ formatTime(schedules.startTime) }} - 
            {{ formatTime(schedules.endTime) }}
          </div> -->
              <div class="details">
                <div class="name">{{ schedules.name }}</div>
                <div class="position">{{ schedules.teams }}</div>
              </div>
            </div>
          </div>
      </div>
      </div>
    </ion-content>
  </ion-page>
</template>

<script setup>
import { ref, computed,onMounted } from 'vue';
import { 
  IonPage,
  IonHeader,
  IonToolbar,
  IonContent,
  IonButtons,
  IonButton,
  IonIcon,
  IonModal,
  IonDatetime
} from '@ionic/vue';
import { chevronBack, chevronForward,swapHorizontal } from 'ionicons/icons';
import { 
  format,
  startOfWeek,
  endOfWeek,
  eachDayOfInterval,
  isToday,
  addDays, 
  parseISO,
  isSameDay 
} from 'date-fns';

import axios from 'axios';
import { useRouter } from 'vue-router';
const router = useRouter();

const gotoLogs = () => {
  router.push('/logs'); // 或使用命名路由
};
// 模式切换
const mode = ref('week');
const currentDate = ref(new Date());
const schedules=ref([])
const fetchData=async () => {
  try {
    // const response = await axios.get('https://www.svom-gwacn.cn/svomBA-dev/shift/calendar',{
    const response = await axios.get('https://www.svom.cn/svomBA/shift/calendar',{
      params: {
        beginDate: '2023-01-01',
        endDate: '2050-12-31',
        withFr: true // 确保参数值类型正确
      }
    });
    schedules.value = response.data.data.list;
    console.log(response.data);
  } catch (error) {
    console.error('An error occurred while fetching the schedule:', error);
  }
};
onMounted(fetchData);
// onMounted(() => {
//   setInterval(async () => {
//     fetchData()
//   }, 1000*60*60);
//  });
// 计算周视图的日期范围
const weekDays = computed(() => {
  const start = startOfWeek(currentDate.value, { weekStartsOn: 7 });
  const end = endOfWeek(currentDate.value, { weekStartsOn: 7 });
  return eachDayOfInterval({ start, end }).map(date => ({
    date,
    weekday: format(date, 'EEE'),
    isToday: isToday(date)
  }));
});

// 获取指定日期的排班
const getSchedules = (date) => {
  return Array.isArray(schedules.value) 
    ? schedules.value.filter(s => {
        try {
          if (!s.date) return false;
          const scheduleDate = new Date(s.date);
          return isSameDay(scheduleDate, date);
        } catch {
          return false;
        }
      })
    : [];
};



// 日期导航
const changeDate = (step) => {
  currentDate.value = addDays(currentDate.value, 
    mode.value === 'week' ? step * 7 : step
  );
};

// 选择器状态控制
const isDatePickerOpen = ref(false);

// 修改日期处理逻辑
const handleDateChange = (event) => {
  currentDate.value = parseISO(event.detail.value);
  isDatePickerOpen.value = false;
};

// 模式切换处理
const toggleMode = () => {
  mode.value = mode.value === 'day' ? 'week' : 'day';
  // 可选：切换到当前日期所在的周/日视图
  currentDate.value = new Date(); 
};

// 时间轴生成逻辑
const timeSlots = computed(() => {
  const date = currentDate.value;
  const slots = [];
  let current = new Date(date);
  current.setHours(0, 0, 0, 0); // 从00:00开始

  // 创建AM/PM时间段（每1小时一个时段）
  for (let i = 0; i < 24; i++) {
    const end = new Date(current.getTime() + 1 * 60 * 60 * 1000);
    const period = format(current, 'a'); // 获取AM/PM
    
    slots.push({
      start: new Date(current),
      end: end,
      label: `${format(current, 'ha')}`,
      period: period.toLowerCase()
    });
    
    current = end;
  }
  return slots;
});

// const formatTime = (timeString) => {
//   return format(new Date(timeString), 'HH:mm');
// };

// 日视图计算属性
const dailySchedules = computed(() => {
  const currentUTC = new Date(Date.UTC(
    currentDate.value.getUTCFullYear(),
    currentDate.value.getUTCMonth(),
    currentDate.value.getUTCDate()
  ));
  
  return schedules.value.filter(s => {
    if (!s.startTime || !s.endTime) return false;
    const start = new Date(s.startTime);
    const end = new Date(s.endTime);
    
    return (start >= currentUTC && start < new Date(currentUTC.getTime() + 86400000)) ||
           (end > currentUTC && start < currentUTC);
  });
});

// 样式计算方法
const getMarkerPosition = (slot) => {
  const totalMinutes = slot.start.getHours() * 60 + slot.start.getMinutes();
  return `${(totalMinutes / 1440) * 100}%`;
};

const getScheduleBlockStyle = (schedule) => {
  const start = new Date(schedule.startTime);
  const end = new Date(schedule.endTime);
  
  // 处理跨日情况
  const baseDate = new Date(currentDate.value);
  baseDate.setUTCHours(0,0,0,0);

  // 计算相对时间
  const startMinutes = Math.max(
    (start - baseDate) / 1000 / 60,
    0
  );
  const endMinutes = Math.min(
    (end - baseDate) / 1000 / 60,
    1440
  );

  return {
    top: `${(startMinutes / 1440) * 100}%`,
    height: `${((endMinutes - startMinutes) / 1440) * 100}%`,
  };
};
const getScheduleStatus = (schedules) => {
  const now = new Date();
  const start = new Date(schedules.startTime);
  const end = new Date(schedules.endTime);

  // 处理跨日排班（仅在 end 早于 start 时调整）
  if (end < start) {
    end.setDate(end.getDate() + 1);
  }

  const nowTime = now.getTime(); // 使用当前时间的完整UTC时间戳
  const startTime = start.getTime();
  const endTime = end.getTime();

  if (nowTime < startTime) {
    return 'upcoming';
  } else if (nowTime > endTime) {
    return 'completed';
  } else {
    return 'ongoing';
  }
};

// 点击周视图排班项
const handleScheduleClick = (schedule) => {
  // 切换到日视图模式
  mode.value = 'day';
  // 更新当前日期为排班日期
  currentDate.value = new Date(schedule.startTime);
};


</script>

<style scoped>
ion-toolbar ion-button[slot="start"] {
  min-width: 80px;
  font-weight: 500;
  --background: #f8f9fa;
  --border-radius: 8px;
  margin-left: 8px;
}
.mode-toggle {
  --border-radius: 8px;
  --padding-start: 12px;
  --padding-end: 12px;
  --background: var(--ion-color-light);
  --box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.button-content {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: var(--ion-color-dark);
}

.toggle-icon {
  font-size: 18px;
  color: var(--ion-color-medium);
  transition: transform 0.3s ease;
}

.mode-toggle:active .toggle-icon {
  transform: rotate(90deg);
}
/* 周视图样式 */
.calendar-week {
  height: 100%;
  overflow: hidden;
}

.week-scroll-container {
  height: 100%;
  overflow: auto;
}

.week-header,
.week-body {
  display: grid;
  grid-template-columns: repeat(7, minmax(50px, 1fr));
  min-width: 800px; /* 7*150px */
}

.week-header {
  position: sticky;
  top: 0;
  background: white;
  z-index: 2;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
}

.week-day {
  text-align: center;
  padding: 8px;
  border-right: 1px solid #eee;
}

.day-column {
  min-height: 100%;
  padding: 8px;
  border-right: 1px solid #eee;
}
.week-day.today {
  color: #3880ff;
  font-weight: bold;
}
/* 日视图样式 */
.calendar-day {
  height: 100%;
}

.day-header {
  padding: 16px;
  border-bottom: 1px solid #eee;
}

.current-date {
  font-size: 1.2em;
  font-weight: bold;
}
.daytitle{
  text-align: center;
}

.name {
  font-weight: 500;
}

.position {
  font-size: 0.8em;
  color: #888;
}

.custom-datetime {
  --width: 160px;
  --height: 40px;
}

.time-slot {
  margin: 12px 0;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
}

ion-datetime {
  margin-right: 12px;
}

/* 调整状态颜色 */
.schedule-block.upcoming {
  background: #fff3e0;
  border-left: 4px solid #ffa726;
}

.schedule-block.ongoing {
  background: #e8f5e9;
  border-left: 4px solid #4caf50;
}

.schedule-block.completed {
  background: #ffebee;
  border-left: 4px solid #ef5350;
}

.schedule-content {
  position: relative;
  z-index: 2;
}

/* 时间轴时间段样式 */
.time-axis-container {
  position: relative;
  height: calc(100vh - 180px);
  margin: 20px;
  background: linear-gradient(
    to bottom,
    rgba(248, 249, 250, 0.3) 0%,
    rgba(248, 249, 250, 0.15) 50%,
    rgba(248, 249, 250, 0.3) 100%
  );
}

.time-marker {
  position: absolute;
  left: 0;
  right: 0;
  z-index: 1;
}

.time-label {
  position: absolute;
  left: -20px;
  font-size: 0.8em;
  color: #666;
  width: 40px;
  text-align: right;
}

.time-line {
  position: absolute;
  left: 0;
  right: 0;
  border-top: 1px solid #eee;
}

.schedule-block {
  position: absolute;
  left: 40px;
  right: 20px;
  z-index: 2;
  padding: 8px;
  border-radius: 4px;
  overflow: hidden;
  transition: all 0.2s;
}

.time-slot.current {
  background: #f8f9fa;
  border-radius: 8px;
}

.time {
  font-size: 0.9em;
  color: #666;
  margin-bottom: 4px;
}
.schedule-item {
  padding: 12px;
  margin: 0;
  border-radius: 6px;
  cursor: pointer;
  transition: transform 0.1s;
}
.schedule-item:active {
  transform: scale(0.98); 
}
.schedule-item::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 3px;
}
.schedule-item.upcoming {
  background: #fff3e0;  /* 未开始 - 橘色 */
  border-left: 4px  #ffa726;
}

.schedule-item.ongoing {
  background: #e8f5e9 !important;  /* 进行中 - 绿色 */
  border-left: 4px  #4caf50 !important;
}

.schedule-item.completed {
  background: #ffebee;  /* 已结束 - 红色 */
  border-left: 4px  #ef5350;
}
/* 日期选择器 */
.compact-date-picker {
  --width: 300px;
  --height: 380px;
  --border-radius: 12px;
}

.compact-datetime {
  padding: 0;
  --background: white;
  --background-rgb: 255 255 255;
}

.compact-datetime::part(calendar-day) {
  width: 32px;
  height: 32px;
}

.modal-buttons {
  display: flex;
  justify-content: space-between;
  padding: 8px 16px;
}
ion-toolbar ion-button {
  --padding-start: 8px;
  --padding-end: 8px;
  margin: 0 4px;
}
</style>


